package com.kaifamiao.exercise;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyTest implements InvocationHandler {
    private Object object;

    public ProxyTest(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("-----begin----");
        Object invoke = method.invoke(object, args);
        System.out.println("-----end-----");
        return invoke;
    }

    // main 方法
    public static void main(String[] args) {
        Car c = new BYD();
        InvocationHandler allProxy = new ProxyTest(c);
        Car car = (Car) Proxy.newProxyInstance(ProxyTest.class.getClassLoader(),c.getClass().getInterfaces(),allProxy);
        car.saleCar();

        Phone p = new HuaWei();
        allProxy = new ProxyTest(p);
        Phone phone = (Phone) Proxy.newProxyInstance(ProxyTest.class.getClassLoader(),p.getClass().getInterfaces(),allProxy);
        phone.salePhone();
    }

}

interface Car{
    void saleCar();
}

interface Phone{
    void salePhone();
}

class BYD implements Car{
    @Override
    public void saleCar() {
        System.out.println("销售比亚迪!");
    }
}

class HuaWei implements Phone{
    @Override
    public void salePhone() {
        System.out.println("销售华为手机！");
    }
}